//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Roles;
namespace DotNetNuke.Modules.Admin.Sales
{
	partial class PayPalSubscription : Framework.PageBase
	{

		private void InitializeComponent()
		{
		}
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			InitializeComponent();
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			try
			{
				UserInfo objUserInfo = null;
				int intUserID = -1;
				if (Request.IsAuthenticated)
				{
					objUserInfo = UserController.GetCurrentUserInfo();
					if (objUserInfo != null)
					{
						intUserID = objUserInfo.UserID;
					}
				}
				int intRoleId = -1;
				if (Request.QueryString["roleid"] != null)
				{
					intRoleId = int.Parse(Request.QueryString["roleid"]);
				}
				string strProcessorUserId = "";
				PortalController objPortalController = new PortalController();
				PortalInfo objPortalInfo = objPortalController.GetPortal(PortalSettings.PortalId);
				if (objPortalInfo != null)
				{
					strProcessorUserId = objPortalInfo.ProcessorUserId;
				}
				Dictionary<string, string> settings = PortalController.GetPortalSettingsDictionary(PortalSettings.PortalId);
				string strPayPalURL;
				if (intUserID != -1 && intRoleId != -1 && !String.IsNullOrEmpty(strProcessorUserId))
				{
					// Sandbox mode
                    if(settings.ContainsKey("paypalsandbox") && !String.IsNullOrEmpty(settings["paypalsandbox"]) && settings["paypalsandbox"] == "true")
					{
                        strPayPalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?";
                    }
					else
					{
						strPayPalURL = "https://www.paypal.com/cgi-bin/webscr?";
                    }

					if (Request.QueryString["cancel"] != null)
					{
						strPayPalURL += "cmd=_subscr-find&alias=" + Common.Globals.HTTPPOSTEncode(strProcessorUserId);
					}
					else
					{
						strPayPalURL += "cmd=_ext-enter";
						RoleController objRoles = new RoleController();
						RoleInfo objRole = objRoles.GetRole(intRoleId, PortalSettings.PortalId);
						if (objRole.RoleID != -1)
						{
							int intTrialPeriod = 1;
							if (objRole.TrialPeriod != 0)
							{
								intTrialPeriod = objRole.TrialPeriod;
							}
							int intBillingPeriod = 1;
							if (objRole.BillingPeriod != 0)
							{
								intBillingPeriod = objRole.BillingPeriod;
							}
							System.Globalization.CultureInfo enFormat = new System.Globalization.CultureInfo("en-US");
							string strService = string.Format(enFormat.NumberFormat, "{0:#####0.00}", objRole.ServiceFee);
							string strTrial = string.Format(enFormat.NumberFormat, "{0:#####0.00}", objRole.TrialFee);
							if (objRole.BillingFrequency == "O" || objRole.TrialFrequency == "O")
							{
								strPayPalURL += "&redirect_cmd=_xclick&business=" + Common.Globals.HTTPPOSTEncode(strProcessorUserId);
								strPayPalURL += "&item_name=" + Common.Globals.HTTPPOSTEncode(PortalSettings.PortalName + " - " + objRole.RoleName + " ( " + objRole.ServiceFee.ToString("#.##") + " " + PortalSettings.Currency + " )");
								strPayPalURL += "&item_number=" + Common.Globals.HTTPPOSTEncode(intRoleId.ToString());
								strPayPalURL += "&no_shipping=1&no_note=1";
								strPayPalURL += "&quantity=1";
								strPayPalURL += "&amount=" + Common.Globals.HTTPPOSTEncode(strService);
								strPayPalURL += "&currency_code=" + Common.Globals.HTTPPOSTEncode(PortalSettings.Currency);
							}
							else
							{
								strPayPalURL += "&redirect_cmd=_xclick-subscriptions&business=" + Common.Globals.HTTPPOSTEncode(strProcessorUserId);
								strPayPalURL += "&item_name=" + Common.Globals.HTTPPOSTEncode(PortalSettings.PortalName + " - " + objRole.RoleName + " ( " + objRole.ServiceFee.ToString("#.##") + " " + PortalSettings.Currency + " every " + intBillingPeriod.ToString() + " " + GetBillingFrequencyCode(objRole.BillingFrequency) + " )");
								strPayPalURL += "&item_number=" + Common.Globals.HTTPPOSTEncode(intRoleId.ToString());
								strPayPalURL += "&no_shipping=1&no_note=1";
								if (objRole.TrialFrequency != "N")
								{
									strPayPalURL += "&a1=" + Common.Globals.HTTPPOSTEncode(strTrial);
									strPayPalURL += "&p1=" + Common.Globals.HTTPPOSTEncode(intTrialPeriod.ToString());
									strPayPalURL += "&t1=" + Common.Globals.HTTPPOSTEncode(objRole.TrialFrequency);
								}
								strPayPalURL += "&a3=" + Common.Globals.HTTPPOSTEncode(strService);
								strPayPalURL += "&p3=" + Common.Globals.HTTPPOSTEncode(intBillingPeriod.ToString());
								strPayPalURL += "&t3=" + Common.Globals.HTTPPOSTEncode(objRole.BillingFrequency);
								strPayPalURL += "&src=1";
								strPayPalURL += "&currency_code=" + Common.Globals.HTTPPOSTEncode(PortalSettings.Currency);
							}
						}
						Common.Lists.ListController ctlList = new Common.Lists.ListController();
						strPayPalURL += "&custom=" + Common.Globals.HTTPPOSTEncode(intUserID.ToString());
						strPayPalURL += "&first_name=" + Common.Globals.HTTPPOSTEncode(objUserInfo.Profile.FirstName);
						strPayPalURL += "&last_name=" + Common.Globals.HTTPPOSTEncode(objUserInfo.Profile.LastName);
						try
						{
							if (objUserInfo.Profile.Country == "United States")
							{
								Common.Lists.ListEntryInfo colList = ctlList.GetListEntryInfo("Region", objUserInfo.Profile.Region);
								strPayPalURL += "&address1=" + Common.Globals.HTTPPOSTEncode(Convert.ToString(!String.IsNullOrEmpty(objUserInfo.Profile.Unit) ? objUserInfo.Profile.Unit + " " : "") + objUserInfo.Profile.Street);
								strPayPalURL += "&city=" + Common.Globals.HTTPPOSTEncode(objUserInfo.Profile.City);
								strPayPalURL += "&state=" + Common.Globals.HTTPPOSTEncode(colList.Value);
								strPayPalURL += "&zip=" + Common.Globals.HTTPPOSTEncode(objUserInfo.Profile.PostalCode);
							}
						}
						catch
						{
						}
						if (settings.ContainsKey("paypalsubscriptionreturn") && !string.IsNullOrEmpty(settings["paypalsubscriptionreturn"]))
						{
							strPayPalURL += "&return=" + Common.Globals.HTTPPOSTEncode(settings["paypalsubscriptionreturn"]);
						}
						else
						{
							strPayPalURL += "&return=" + Common.Globals.HTTPPOSTEncode(Common.Globals.AddHTTP(Common.Globals.GetDomainName(Request)));
						}
						if (settings.ContainsKey("paypalsubscriptioncancelreturn") && !string.IsNullOrEmpty(settings["paypalsubscriptioncancelreturn"]))
						{
							strPayPalURL += "&cancel_return=" + Common.Globals.HTTPPOSTEncode(settings["paypalsubscriptioncancelreturn"]);
						}
						else
						{
							strPayPalURL += "&cancel_return=" + Common.Globals.HTTPPOSTEncode(Common.Globals.AddHTTP(Common.Globals.GetDomainName(Request)));
						}
						if (settings.ContainsKey("paypalsubscriptionnotifyurl") && !string.IsNullOrEmpty(settings["paypalsubscriptionnotifyurl"]))
						{
							strPayPalURL += "&notify_url=" + Common.Globals.HTTPPOSTEncode(settings["paypalsubscriptionnotifyurl"]);
						}
						else
						{
							strPayPalURL += "&notify_url=" + Common.Globals.HTTPPOSTEncode(Common.Globals.AddHTTP(Common.Globals.GetDomainName(Request)) + "/admin/Sales/PayPalIPN.aspx");
						}
						strPayPalURL += "&sra=1";
					}
					Response.Redirect(strPayPalURL, true);
				}
				else
				{
					if ((settings.ContainsKey("paypalsubscriptioncancelreturn") && !string.IsNullOrEmpty(settings["paypalsubscriptioncancelreturn"])))
					{
						strPayPalURL = settings["paypalsubscriptioncancelreturn"];
					}
					else
					{
						strPayPalURL = Common.Globals.AddHTTP(Common.Globals.GetDomainName(Request));
					}
					Response.Redirect(strPayPalURL, true);
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessPageLoadException(exc);
			}
		}
		private string GetBillingFrequencyCode(string Value)
		{
			Common.Lists.ListController ctlEntry = new Common.Lists.ListController();
			Common.Lists.ListEntryInfo entry = ctlEntry.GetListEntryInfo("Frequency", Value);
			return entry.Value;
		}
	}
}
